<?php

namespace app\middleware;

use app\backend\model\SysUser;
use app\backend\model\SysUserMenu;
use app\helper\StringHelper;
use ReflectionClass;
use support\Redis;
use app\component\RedisKey;
use support\XunshanContainer;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class BackendAuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $app = $request->app;
        $controller = $request->controller; //带namespace的class命 例如app\backend\controller\Index
        $action = $request->action;
        $controllerClass = new ReflectionClass($controller);
        if ($controllerClass->implementsInterface(\app\component\BaseAction::class)) {
            $tmp = explode('\\', $controller);
            $action = $tmp[count($tmp) - 1];//取最后一个
            $action = substr($action, 0, -6);
            $action = StringHelper::camel2id($action);
            $controller = $tmp[count($tmp) - 2];//倒数第二个
            $controller = StringHelper::camel2id($controller);
        } elseif ($controllerClass->implementsInterface(\app\component\BaseController::class)) {
            $tmp = explode('\\', $controller);
            $controller = $tmp[count($tmp) - 1];//取最后一个
            $controller = substr($controller, 0, -10);
            $controller = StringHelper::camel2id($controller);
            $action = substr($action, 6);
            $action = StringHelper::camel2id($action);
        } else {
            $tmp = explode('\\', $controller);
            $controller = $tmp[count($tmp) - 1];//取最后一个
            $controller = StringHelper::camel2id($controller);
            $action = StringHelper::camel2id($action);
        }

        if (in_array($controller, ['login', 'common', 'auto-complete'])) {
            //不需要登录 也不需要什么权限
            return $next($request);
        }

        if ($controller == 'index' || $controller == 'dashboard') {
            //需要登录 不需要什么权限
            if (XunshanContainer::user()->getIsGuest()) {
                //需要去登录
                return redirect('/backend/login/index');
            } else {
                if ($action != 'lock') {
                    $auid = XunshanContainer::user()->getIdentity()->getId();
                    if (Redis::exists(RedisKey::XUNSHAN_USER_LOCK . $auid)) {
                        return redirect('/backend/index/lock');
                    }
                }
                return $next($request);
            }
        }
        //剩下的需要权限 以及登录
        if (XunshanContainer::user()->getIsGuest()) {
            if ($request->isAjax()) {
                return json_error('您还没有登录，请先去登录');
            } else {
                //需要去登录
                return redirect('/backend/login/index');
            }
        } else {
            $auid = XunshanContainer::user()->getIdentity()->getId();
            if (Redis::exists(RedisKey::XUNSHAN_USER_LOCK . $auid)) {
                if (!$request->isAjax()) {
                    if ($request->path() != '/backend/login/logout') {
                        //需要去解锁
                        return redirect('/backend/index/lock');
                    }
                } else {
                    if ($request->path() != '/backend/login/unlock') {
                        return json_error('您已锁定桌面，请先去解锁');
                    }
                }
            }
        }

        //超级管理员不操作
        /** @var SysUser $sysUser */
        $sysUser = SysUser::query()->where('auid', XunshanContainer::user()->getIdentity()->getId())->first();

        if ($sysUser && $sysUser->status == 1) {
            //被禁用了
            if ($request->isAjax()) {
                return json_error('您的账号已经被禁用，请更换账号');
            } else {
                //页面没有权限
                return redirect('/backend/common/no-auth');
            }
        }

        //超级管理员 或者有所有的数据权限
        if ($sysUser && ($sysUser->admin_type == 1 || $sysUser->data_scope == 1)) {
            return $next($request);
        }

        $module = $app;
        //根据 模块 controller action 拼凑出权限字段
        $tmp = [];
        if ($module) {
            $tmp[] = $module;
        }
        if ($controller) {
            $tmp[] = $controller;
        }
        if ($action) {
            $tmp[] = $action;
        }
        $perm = 'xs:' . implode(':', $tmp);
        //去用户权限表里面去查 有没有这个权限
        $isHaveAuth = SysUserMenu::query()
            ->where([
                ['auid', '=', XunshanContainer::user()->getIdentity()->getId()],
                ['perms', '=', $perm],
            ])
            ->first();
        if (!$isHaveAuth) {
            if ($request->isAjax()) {
                return json_error('您没有权限操作此模块');
            } else {
                //页面没有权限
                return redirect('/backend/common/no-auth');
            }
        }
        return $next($request);
    }
}
